// pages/admin/user-manage/user-manage.js
const { get, post, put, del } = require('../../../utils/request')
const { formatDate, showSuccess, showError, showConfirm, debounce } = require('../../../utils/util')

Page({
  data: {
    userList: [],
    allUsers: [], // 保存所有用户数据用于搜索
    searchText: '',
    loading: false,

    // 弹窗相关
    showModal: false,
    isEdit: false,
    formData: {
      username: '',
      password: '',
      name: '',
      phone: '',
      email: '',
      role: 'USER'
    },
    roleIndex: 1,
    roleList: ['管理员', '普通用户'],
    submitting: false
  },

  onLoad() {
    // 检查管理员权限
    const app = getApp()
    if (!app.globalData.userInfo || app.globalData.userInfo.role !== 'ADMIN') {
      wx.showModal({
        title: '权限不足',
        content: '您没有管理员权限',
        showCancel: false,
        success: () => {
          wx.navigateBack()
        }
      })
      return
    }

    this.loadUserList()
  },

  onShow() {
    this.loadUserList()
  },

  onPullDownRefresh() {
    this.loadUserList(() => {
      wx.stopPullDownRefresh()
    })
  },

  // 加载用户列表
  loadUserList(callback) {
    this.setData({ loading: true })

    get('/user/all').then(res => {
      const userList = res.data || []

      // 格式化时间
      userList.forEach(item => {
        if (item.createTime) {
          item.createTime = formatDate(item.createTime)
        }
      })

      this.setData({
        userList,
        allUsers: userList
      })
    }).catch(err => {
      showError('加载用户列表失败')
    }).finally(() => {
      this.setData({ loading: false })
      callback && callback()
    })
  },

  // 搜索输入
  onSearchInput: debounce(function(e) {
    this.setData({
      searchText: e.detail.value
    })
  }, 300),

  // 搜索用户
  onSearch() {
    const searchText = this.data.searchText.trim().toLowerCase()

    if (!searchText) {
      this.setData({
        userList: this.data.allUsers
      })
      return
    }

    const filteredUsers = this.data.allUsers.filter(user => {
      return (user.username && user.username.toLowerCase().includes(searchText)) ||
             (user.name && user.name.toLowerCase().includes(searchText)) ||
             (user.phone && user.phone.includes(searchText)) ||
             (user.email && user.email.toLowerCase().includes(searchText))
    })

    this.setData({
      userList: filteredUsers
    })
  },

  // 添加用户
  addUser() {
    this.setData({
      showModal: true,
      isEdit: false,
      formData: {
        username: '',
        password: '',
        name: '',
        phone: '',
        email: '',
        role: 'USER'
      },
      roleIndex: 1
    })
  },

  // 编辑用户
  editUser(e) {
    const user = e.currentTarget.dataset.user
    const roleIndex = user.role === 'ADMIN' ? 0 : 1

    this.setData({
      showModal: true,
      isEdit: true,
      formData: {
        id: user.id,
        username: user.username,
        password: '',
        name: user.name || '',
        phone: user.phone || '',
        email: user.email || '',
        role: user.role
      },
      roleIndex
    })
  },

  // 删除用户
  async deleteUser(e) {
    const { id, name } = e.currentTarget.dataset

    try {
      await showConfirm(`确定要删除用户"${name}"吗？此操作不可恢复。`)
    } catch {
      return
    }

    del(`/user/${id}`).then(res => {
      showSuccess('删除成功')
      this.loadUserList()
    }).catch(err => {
      showError(err.msg || '删除失败')
    })
  },

  // 表单输入事件
  onUsernameInput(e) {
    this.setData({
      'formData.username': e.detail.value
    })
  },

  onPasswordInput(e) {
    this.setData({
      'formData.password': e.detail.value
    })
  },

  onNameInput(e) {
    this.setData({
      'formData.name': e.detail.value
    })
  },

  onPhoneInput(e) {
    this.setData({
      'formData.phone': e.detail.value
    })
  },

  onEmailInput(e) {
    this.setData({
      'formData.email': e.detail.value
    })
  },

  onRoleChange(e) {
    const index = parseInt(e.detail.value)
    this.setData({
      roleIndex: index,
      'formData.role': index === 0 ? 'ADMIN' : 'USER'
    })
  },

  // 关闭弹窗
  closeModal() {
    this.setData({
      showModal: false
    })
  },

  // 阻止事件冒泡
  stopPropagation() {
    // 阻止点击弹窗内容时关闭弹窗
  },

  // 表单验证
  validateForm() {
    const { username, password, name, phone, email } = this.data.formData

    if (!username.trim()) {
      showError('请输入用户名')
      return false
    }

    if (username.trim().length < 3) {
      showError('用户名至少需要3个字符')
      return false
    }

    if (!this.data.isEdit && !password.trim()) {
      showError('请输入密码')
      return false
    }

    if (!this.data.isEdit && password.trim().length < 6) {
      showError('密码至少需要6个字符')
      return false
    }

    if (phone && !/^1[3-9]\d{9}$/.test(phone.trim())) {
      showError('请输入正确的手机号')
      return false
    }

    if (email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim())) {
      showError('请输入正确的邮箱地址')
      return false
    }

    return true
  },

  // 保存用户
  async saveUser() {
    if (this.data.submitting) return

    if (!this.validateForm()) return

    this.setData({ submitting: true })

    const submitData = {
      username: this.data.formData.username.trim(),
      name: this.data.formData.name.trim(),
      phone: this.data.formData.phone.trim(),
      email: this.data.formData.email.trim(),
      role: this.data.formData.role
    }

    // 添加用户时需要密码
    if (!this.data.isEdit) {
      submitData.password = this.data.formData.password.trim()
    }

    try {
      if (this.data.isEdit) {
        submitData.id = this.data.formData.id
        await put('/user', submitData)
        showSuccess('修改成功')
      } else {
        await post('/register', submitData)
        showSuccess('添加成功')
      }

      this.closeModal()
      this.loadUserList()

    } catch (err) {
      showError(err.message || '保存失败，请重试')
    } finally {
      this.setData({ submitting: false })
    }
  }
})
